package r3.spring.bean;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import r3.common.R3Url;

import java.lang.reflect.Method;

/**
 * WorkerBean
 *
 * @author zhoufn
 * @create 2017-12-26 10:36
 **/
public class WorkerBean implements InitializingBean{

    @Setter@Getter private String id;

    @Setter@Getter private Object ref;

    @Setter@Getter private String interfce;

    /**
     * Invoked by a BeanFactory after it has set all bean properties supplied
     * (and satisfied BeanFactoryAware and ApplicationContextAware).
     * <p>This method allows the bean instance to perform initialization only
     * possible when all bean properties have been set and to throw an
     * exception in the event of misconfiguration.
     *
     * @throws Exception in the event of misconfiguration (such
     *                   as failure to set an essential property) or if initialization fails.
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        RegistryBean registryBean = ApplicationBean.getContext().getBean(RegistryBean.class);
        ApplicationBean applicationBean = ApplicationBean.getContext().getBean(ApplicationBean.class);
        R3Url url = new R3Url();
        url.setNamespace(registryBean.getNamespace());
        url.setInterfce(this.interfce);
        url.setApplicaionName(applicationBean.getName());
        url.setBeanId(this.id);
        url.setApplicationHost(applicationBean.getHost());
        url.setApplicationPort(applicationBean.getPort());
        registryBean.getRegistryCenter().registe(url);

    }

    /**
     * 反射具体实现类
     * @param methodName
     * @param parameterTypes
     * @param arguments
     * @return
     * @throws Exception
     */
    public Object invoke(String methodName,Class<?>[] parameterTypes,Object[] arguments) throws Exception{
        Class clazz = ref.getClass();
        Method method = clazz.getMethod(methodName,parameterTypes);
        return method.invoke(ref,arguments);
    }
}
